// 格式化时间 yyyy-MM-dd  yyyy-MM-dd hh:mm:ss
function dateFormat(fmt, time) {
	// time = '2017-09-19T16:00:00Z'
	// time = '2019-10-30T10:16:31+08:00'
	// time = '2019-12-09T06:29:41+0000'
	// time = '2019-12-20T02:24:09.346Z'
	// time= '2019/12/24T06:25:17Z'
	// time = '2019-12-20T02:24:09.346Z'
	if (time && time != null) {
		if (!/^\d+$/.test(time)) {
			time = time.replace(/-/g, '/');
			// 若时间有 .xxx 格式，则将 .xxx 替换成为空
			var index = time.indexOf('.');
			if (index >= 0) {
				var str = time.substring(index, index + 4)
				time = time.replace(str, '');
			}
			// 若时间有 Z 格式，则将 Z 替换成为空
			var a = time.indexOf('Z');
			if (a >= 0) {
				time = time.replace('Z', '+0000');
			}
			// 将 T 替换 为 空
			time = time.replace('T', ' ');
			var date;
			if (time == 'now') {
				date = new Date();
			} else {
				var timestamp = new Date(time).getTime();
				date = new Date(time);
			}
			// var index = time.indexOf('+08');
			var o = {
				"M+": date.getMonth() + 1, //月份 
				"d+": date.getDate(), //日 
				"h+": date.getHours(), //小时 
				"m+": date.getMinutes(), //分 
				"s+": date.getSeconds(), //秒 
				"q+": Math.floor((date.getMonth() + 3) / 3), //季度 
				"S": date.getMilliseconds() //毫秒 
			};
			if (/(y+)/.test(fmt)) {
				fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
			}

			for (var k in o) {
				if (new RegExp("(" + k + ")").test(fmt)) {
					fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
				}
			}
			return fmt;
		} else {
			return this.timestampFormat(fmt, time)
		}
	} else {
		return null;
	}


}

// 格式化时间 yyyy-MM-dd  yyyy-MM-dd hh:mm:ss
function dateFormatByTimestamp(fmt, timestamp) {
	var date = new Date(timestamp);
	if (timestamp && timestamp > 0) {
		var o = {
			"M+": date.getMonth() + 1, //月份 
			"d+": date.getDate(), //日 
			"h+": date.getHours(), //小时 
			"m+": date.getMinutes(), //分 
			"s+": date.getSeconds(), //秒 
			"q+": Math.floor((date.getMonth() + 3) / 3), //季度 
			"S": date.getMilliseconds() //毫秒 
		};
		if (/(y+)/.test(fmt))
			fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
		for (var k in o)
			if (new RegExp("(" + k + ")").test(fmt))
				fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
		return fmt;
	} else {
		return null;
	}
}

// 计算时间差
function timeDifference(fmt, startT, endT) {
	if (startT && startT.length > 0 && endT && endT.length > 0) {

	}
}

function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}

function formatTimeStamp(time) {
	if (time && time != null) {
		if (!/^\d+$/.test(time)) {
			time = time.replace(/-/g, '/');
			// 若时间有 .xxx 格式，则将 .xxx 替换成为空
			var index = time.indexOf('.');
			if (index >= 0) {
				var str = time.substring(index, index + 4)
				time = time.replace(str, '');
			}
			// 若时间有 Z 格式，则将 Z 替换成为空
			var a = time.indexOf('Z');
			if (a >= 0) {
				time = time.replace('Z', '+0000');
			}
			// 将 T 替换 为 空
			time = time.replace('T', ' ');
			var timestamp = new Date(time).getTime();
			return timestamp;
		} else {
			return time
		}
	} else {
		return null;
	}
}

function dislodgeZero(str) {
	let strArray = str.split("-")
	strArray = strArray.map(function(val) {
		if (val[0] == "0") {
			return (val = val.slice(1))
		} else {
			return val
		}
	})
	return strArray.join("-")
}


var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function(milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function(dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function(number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDate()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
};

/**
 * 根据身份证号得到姓别和精确计算年龄
 */
function analyzeIDCard(IDCard) {
	var sexAndAge = {};
	//获取用户身份证号码
	var userCard = IDCard;
	//如果身份证号码为undefind则返回空
	if (!userCard) {
		return sexAndAge;
	}
	//获取性别
	if (parseInt(userCard.substr(16, 1)) % 2 == 1) {
		sexAndAge.sex = '1'
	} else {
		sexAndAge.sex = '2'
	}
	//获取出生年月日
	//userCard.substring(6,10) + "-" + userCard.substring(10,12) + "-" + userCard.substring(12,14);
	var yearBirth = userCard.substring(6, 10);
	var monthBirth = userCard.substring(10, 12);
	var dayBirth = userCard.substring(12, 14);
	//获取当前年月日并计算年龄
	var myDate = new Date();
	var monthNow = myDate.getMonth() + 1;
	var dayNow = myDate.getDay();
	var age = myDate.getFullYear() - yearBirth;
	// if (monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)) {
	// 	age--;
	// }
	//得到年龄
	sexAndAge.age = age;
	//返回性别和年龄
	return sexAndAge;
}


module.exports = {
	formatTime: formatTime,
	formatLocation: formatLocation,
	dateUtils: dateUtils,
	dateFormat: dateFormat,
	timestampFormat: dateFormatByTimestamp,
	formatTimeStamp: formatTimeStamp,
	analyzeIDCard: analyzeIDCard,
	dislodgeZero:dislodgeZero
}
